var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const init =require('./db/models/init')
const adminRouter = require('./routes/Api');
const Result = require('./lib/Result');
var app = express();
init()
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json({limit:'5mb'}));//默认请求大小1mb
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//配置全局中间件跨域
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
})
var fs = require('fs');
//简易图床
app.use("/static/:img",(req,res,next)=>{
  const filePath=path.resolve(__dirname,`./assets/${req.params.img}`)
  res.set('content-type', {"png": "image/png","jpg": "image/jpeg"})
  var stream=fs.createReadStream(filePath)
  var resData=[];
  if (stream) {
    stream.on( 'data', function( chunk ) {
      resData.push( chunk );
    });
    stream.on( 'end', function() {
       var finalData = Buffer.concat( resData );
       res.write( finalData );
       res.end();
    });
  }
})


app.use('/admin/api', adminRouter);
app.use((req,res)=>{
  res.json(Result.apiNotFount())
})
module.exports = app;
